#include "net/poller.h"
#include "base/base.h"
#include "net/signal.h"
#include <sys/timerfd.h>
#include "net/timer_queue.h"
#include "net/poll_thread_pool.h"
#include <signal.h>

#include "test/test_buffer.h"

static int sig_cnt = 0;

static void sig_callback(void* ctx) {
  int* cnt = (int*) ctx;
  (*cnt)++;
  struct timespec t;
  ::clock_gettime(CLOCK_REALTIME, &t);
  LOG(INFO)<< "catch signal: " << *cnt << "current: " << t.tv_sec;
}

static void timer_print() {
  time_t t;
  ::time(&t);
  LOG(INFO)<< "timer print: " << ::ctime(&t);
}

static void test_timer(net::Poller* p) {
  // not delete timer_queue.
  net::TimerQueue* timer_queue = new net::TimerQueue(p);
  net::Timer* timer1 = new net::Timer(new FuncClosure0(timer_print), true, 5);
  timer_queue->AddTimer(timer1);

  net::Timer* timer2 = new net::Timer(new FuncClosure0(timer_print), true, 7);
  timer_queue->AddTimer(timer2);
}

static void test_stdin(net::Poller* p) {
  // not delete ev
  CHECK_NOTNULL(p);
  TestStdin* t = new TestStdin(p);
}

static void test_sig_manager(net::Poller* p) {
  net::SigManager* sig_manager = net::SigManager::Instance(p);
  net::Signal* sig = sig_manager->RegSig(SIGINT);
  sig->cb = &sig_callback;
  sig->ctx = &sig_cnt;
  sig_manager->Start();
}

int main(int argc, char* argv[]) {
  ::google::ParseCommandLineFlags(&argc, &argv, true);
  net::Poller* base_poll = net::CreatePoller();
  CHECK(base_poll->Init());
  test_sig_manager(base_poll);

  scoped_ptr<net::PollThreadPool> pool(new net::PollThreadPool(base_poll));
  net::Poller* p = pool->getPoller();
  test_stdin(p);

  p = pool->getPoller();
  test_timer(p);

  pool->Start();

  for (int i = 0; i < 15; ++i) {
    ::sleep(1);
  }

  return 0;
}
